<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text">
    <button>发送</button><br>
    <div class="msg"></div>
    <script>
        const ws = new WebSocket("ws://localhost:3000")
        //当连接成功的时候触发
        ws.addEventListener("open",()=>{
            const inpEle = document.querySelector("input")
            const btn = document.querySelector("button")
            btn.onclick = function(){
                if(!inpEle.value) return alert("请输入你要发送的消息")
                //发送消息
                ws.send(inpEle.value)
                //清空表单
                inpEle.value = "";
            }
        })
        ws.addEventListener("message",(res)=>{
            // console.log(msg.data);
            const msg = document.querySelector(".msg")
            msg.innerHTML += "<p>"+res.data+"</p>"

        })
    </script>
</body>
</html>